#!/usr/bin/env node

const fs = require("fs");
const path = require("path");
const yaml = require("js-yaml");

const args = process.argv.slice(2);
const bumpType = args[0] || "minor"; // default to minor

if (!["major", "minor", "patch"].includes(bumpType)) {
    console.log("用法: node bump-all-versions.js [major|minor|patch]");
    console.log("默认值: minor");
    process.exit(1);
}

function bumpVersion(currentVersion, type) {
    const [major, minor, patch] = currentVersion.split(".").map(Number);

    switch (type) {
        case "major":
            return `${major + 1}.0.0`;
        case "minor":
            return `${major}.${minor + 1}.0`;
        case "patch":
            return `${major}.${minor}.${patch + 1}`;
        default:
            return currentVersion;
    }
}

async function bumpAllVersions() {
    const updatedItems = [];

    // First, bump the core version (package.json)
    const packagePath = path.join(__dirname, "..", "package.json");
    try {
        const packageContent = fs.readFileSync(packagePath, "utf8");
        const packageJson = JSON.parse(packageContent);
        const oldCoreVersion = packageJson.version || "1.0.0";
        const newCoreVersion = bumpVersion(oldCoreVersion, bumpType);

        packageJson.version = newCoreVersion;

        fs.writeFileSync(
            packagePath,
            JSON.stringify(packageJson, null, 2) + "\n"
        );

        updatedItems.push({
            type: "core",
            name: "SDAT Core",
            oldVersion: oldCoreVersion,
            newVersion: newCoreVersion,
        });
        console.log(
            `✓ SDAT 核心 (package.json): ${oldCoreVersion} → ${newCoreVersion}`
        );
    } catch (error) {
        console.error(`✗ 更新 SDAT 核心失败: ${error.message}`);
    }

    // Then, bump all expansion packs
    const expansionPacksDir = path.join(__dirname, "..", "expansion-packs");

    try {
        const entries = fs.readdirSync(expansionPacksDir, {
            withFileTypes: true,
        });

        for (const entry of entries) {
            if (
                entry.isDirectory() &&
                !entry.name.startsWith(".") &&
                entry.name !== "README.md"
            ) {
                const packId = entry.name;
                const configPath = path.join(
                    expansionPacksDir,
                    packId,
                    "config.yaml"
                );

                if (fs.existsSync(configPath)) {
                    try {
                        const configContent = fs.readFileSync(
                            configPath,
                            "utf8"
                        );
                        const config = yaml.load(configContent);
                        const oldVersion = config.version || "1.0.0";
                        const newVersion = bumpVersion(oldVersion, bumpType);

                        config.version = newVersion;

                        const updatedYaml = yaml.dump(config, { indent: 2 });
                        fs.writeFileSync(configPath, updatedYaml);

                        updatedItems.push({
                            type: "expansion",
                            name: packId,
                            oldVersion,
                            newVersion,
                        });
                        console.log(
                            `✓ ${packId}: ${oldVersion} → ${newVersion}`
                        );
                    } catch (error) {
                        console.error(
                            `✗ 更新 ${packId} 失败: ${error.message}`
                        );
                    }
                }
            }
        }

        if (updatedItems.length > 0) {
            const coreCount = updatedItems.filter(
                (i) => i.type === "core"
            ).length;
            const expansionCount = updatedItems.filter(
                (i) => i.type === "expansion"
            ).length;

            console.log(
                `\n✓ 成功更新 ${updatedItems.length} 个项目的 ${bumpType} 版本`
            );
            if (coreCount > 0) console.log(`  - ${coreCount} 核心`);
            if (expansionCount > 0) console.log(`  - ${expansionCount} 扩展包`);

            console.log("\n后续步骤:");
            console.log("1. 测试更改");
            console.log(
                '2. 提交: git add -A && git commit -m "chore: 升级所有版本 (' +
                    bumpType +
                    ')"'
            );
        } else {
            console.log("未找到需要更新的项目");
        }
    } catch (error) {
        console.error("读取扩展包目录错误:", error.message);
        process.exit(1);
    }
}

bumpAllVersions();
